package com.ltx.vizflowservice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ltx.vizflowservice.common.convention.errorcode.BaseErrorCode;
import com.ltx.vizflowservice.common.convention.result.Result;
import com.ltx.vizflowservice.common.convention.result.Results;
import com.ltx.vizflowservice.dao.ProjectMapper;
import com.ltx.vizflowservice.domain.dto.ProjectDTO;
import com.ltx.vizflowservice.domain.entity.Project;
import com.ltx.vizflowservice.domain.entity.ProjectTemplate;
import com.ltx.vizflowservice.domain.entity.User;
import com.ltx.vizflowservice.domain.vo.ProjectTemplateVO;
import com.ltx.vizflowservice.domain.vo.ProjectVO;
import com.ltx.vizflowservice.service.ProjectService;
import com.ltx.vizflowservice.service.ProjectTemplateService;
import com.ltx.vizflowservice.service.UserService;
import com.ltx.vizflowservice.util.QiNiuUtil;
import com.ltx.vizflowservice.util.UserContext;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 项目表 服务实现类
 * </p>
 *
 * @author 罗添煦
 * @since 2024-11-15
 */
@Service
@Slf4j
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements ProjectService {

    @Resource
    private ProjectTemplateService projectTemplateService;

    @Resource
    private UserService userService;

    @Override
    public Result<?> createProject(ProjectDTO projectDTO, String userId ,Integer projectStatus) {
        Long l = baseMapper.selectCount(
                Wrappers.lambdaQuery(Project.class)
                        .eq(Project::getUserId, userId));
        if (l >= 10) {
            return Results.failure(BaseErrorCode.PROJECT_NUM_ERROR);
        }
        Project project = Project.builder()
                .backgroundColor(projectDTO.getBackgroundColor())
                .canvasSize(projectDTO.getCanvasSize().toString())
                .projectContent(JSON.toJSONString(projectDTO))
                .projectDescription(projectDTO.getDescription())
                .projectImage(projectDTO.getCoverImage() == null ? "1731662OLhLp" : projectDTO.getCoverImage())
                .projectName(projectDTO.getName())
                .projectUrl(projectDTO.getProjectUrl())
                .projectStatus(projectStatus)
                .projectId(projectDTO.getId())
                .userId(userId)
                .build();
        baseMapper.insert(project);
        return Results.success();
    }

    @Override
    public Result<?> getProjectList() {
        User user = UserContext.getUser();
        List<Project> projectList = baseMapper.selectList(Wrappers.lambdaQuery(Project.class)
                .eq(Project::getUserId, user.getUserId())
                .eq(Project::getDeleted, 0));
        List<ProjectVO> projectVOS = projectList.stream().map(project -> BeanUtil.copyProperties(project, ProjectVO.class)).toList();
        projectVOS.forEach(projectVO -> {
            try {
                projectVO.setProjectImage(QiNiuUtil.fileUrl(projectVO.getProjectImage()));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        });
        return Results.success(projectVOS);
    }

    @Override
    public Result<?> updateProjectStatus(Integer projectId, Integer projectStatus) {
        return switch (projectStatus) {
            case 0, 1, 2 -> {
                baseMapper.update(null, Wrappers.lambdaUpdate(Project.class)
                        .set(Project::getProjectStatus, projectStatus)
                        .eq(Project::getProjectId, projectId));
                yield Results.success();
            }
            default -> Results.failure(BaseErrorCode.PROJECT_STATUS_NOT_EXIST_ERROR);
        };
    }

    @Override
    public Result<?> getProjectDetails(Integer projectId) {
        Project project = baseMapper.selectOne(Wrappers.lambdaQuery(Project.class)
                .eq(Project::getProjectId, projectId));
        return Results.success(project.getProjectContent());
    }

    @Override
    public Result<?> saveProject(ProjectDTO projectDTO) {
        if (projectDTO.getId() != null){
            baseMapper.update(null, Wrappers.lambdaUpdate(Project.class)
                    .set(Project::getProjectContent, JSON.toJSONString(projectDTO))
                    .eq(Project::getProjectId, projectDTO.getId()));
            return Results.success();
        }else {
            return createProject(projectDTO, UserContext.getUser().getUserId() , 0);
        }
    }

    @Override
    public Result<?> publishTemplate(Long projectId) {
        if (projectTemplateService.getProjectTemplate(projectId) != null){
            ProjectTemplate projectTemplate = new ProjectTemplate();
            projectTemplate.setProjectId(projectId);
            projectTemplate.setUserId(UserContext.getUser().getUserId());
            projectTemplateService.save(projectTemplate);
            return Results.success();
        }else {
            return Results.failure(BaseErrorCode.PROJECT_TEMPLATE_EXIST_ERROR);
        }
    }

    @Override
    public Result<?> getTemplates(Page<ProjectTemplate> page) {
        Page<ProjectTemplate> pageList = projectTemplateService.page(page);
        List<ProjectTemplateVO> list = pageList.getRecords().stream().map(projectTemplate -> {
            Project project = baseMapper.selectOne(Wrappers.lambdaQuery(Project.class)
                    .eq(Project::getProjectId, projectTemplate.getProjectId()));
            User user = userService.getOne(Wrappers.lambdaQuery(User.class)
                    .eq(User::getUserId, projectTemplate.getUserId()));
            try {
                return ProjectTemplateVO.builder()
                        .projectId(projectTemplate.getProjectId())
                        .projectName(project.getProjectName())
                        .projectImage(QiNiuUtil.fileUrl(project.getProjectImage()))
                        .userId(projectTemplate.getUserId())
                        .userName(user.getUserName())
                        .userHead(user.getUserHead())
                        .viewNum(projectTemplate.getViewNum())
                        .useNum(projectTemplate.getUseNum())
                        .build();
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }).toList();
        return Results.success(list);
    }

    @Override
    public Result<?> useTemplate(Long projectId) {
        User user = UserContext.getUser();
        Project project = baseMapper.selectOne(Wrappers.lambdaQuery(Project.class)
                .eq(Project::getProjectId, projectId));
        project.setUserId(user.getUserId());
        // 生成8位数
        Integer newProjectId = Integer.parseInt(RandomUtil.randomNumbers(8));
        project.setProjectId(newProjectId);
        project.setCreateAt(LocalDateTime.now());
        project.setUpdateAt(LocalDateTime.now());
        baseMapper.insert(project);
        projectTemplateService.update(Wrappers.lambdaUpdate(ProjectTemplate.class)
                .eq(ProjectTemplate::getProjectId, projectId)
                .set(ProjectTemplate::getUseNum, projectTemplateService.getProjectTemplate(projectId).getUseNum() + 1));
        return Results.success();
    }
}
